﻿using AiChiTu.TraceabilitySystem.Domain.AiChiTuManagement;
using AiChiTu.TraceabilitySystem.ErrorCode;
using AiChiTu.TraceabilitySystem.ErrorCode.Extensions;
using AiChiTu.TraceabilitySystem.Infrastructure.Interfaces;
using AiChiTu.TraceabilitySystem.Write.API.Applications.Commands.ProductBasices;
using AutoMapper;
using MediatR;
using Yitter.IdGenerator;

namespace AiChiTu.TraceabilitySystem.Write.API.Applications.CommandsHandlers.ProductBasices
{
	public class CreateProductBasicsCommandHandle : IRequestHandler<CreateProductBasicsCommand, APIResult<bool>>
	{
		private readonly IBaseRepository<ProductBasics> productbasicRepository;
		private readonly IMapper mapper;

		public CreateProductBasicsCommandHandle(IBaseRepository<ProductBasics> productbasicRepository, IMapper mapper)
		{
			this.productbasicRepository = productbasicRepository;
			this.mapper = mapper;
		}
		/// <summary>
		/// 添加商品基础信息请求命令处理
		/// </summary>
		/// <param name="request">添加商品基础信息请求命令</param>
		/// <param name="cancellationToken">取消</param>
		/// <returns>返回任务</returns>
		public async Task<APIResult<bool>> Handle(CreateProductBasicsCommand request, CancellationToken cancellationToken)
		{
			APIResult<bool> result = new APIResult<bool>();
			result.Code = ResultCode.CreateFailed;
			result.Message = ResultCode.CreateFailed.GetDescription();
			result.Data = false;

			ProductBasics productBasics = mapper.Map<ProductBasics>(request);
			productBasics.ProductBasicsId = YitIdHelper.NextId().ToString();
			productBasics.IsDeleted = false;
			productBasics.CreatePerson = request.CurrentLoginPerson;
			productBasics.CreateTime = DateTime.Now;
			if (await productbasicRepository.CreateEntityAsync(productBasics))
			{
				result.Code = ResultCode.CreateSuccess;
				result.Message = ResultCode.CreateSuccess.GetDescription();
				result.Data = true;
			}

			return await Task.FromResult(result);
		}
	}
}
